package com.wqb.server.controller;

import com.wqb.server.pojo.Admin;
import com.wqb.server.pojo.AdminLoginParam;
import com.wqb.server.pojo.RespBean;
import com.wqb.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @author: 万秋泊
 * @Date: 2022/3/11 13:50
 * @Description:
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
        return adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(), adminLoginParam.getCode(), request);
    }

    @ApiOperation(value = "获取当前登录的用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        System.out.println(admin);
        //出于安全考虑，即便密码是加密的，也不能直接返回给前端
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }

    /**
     * 退出登录只在前端做处理，后端只是为了返回一个状态码200，前端拿到状态码200之后，
     * 前端直接在他的请求头里删除token。
     * 之后再调用其他接口的时候，后端的拦截器就会拦截
     * 请勿改成小写，否则会出现错误： Resolved [org.springframework.web.HttpRequestMethodNotSupportedException:
     * Request method 'GET' not supported]
     *
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logOut")
    public RespBean logout() {
        System.out.println("接收到请求");
        return RespBean.success("注销成功");
    }

}
